﻿IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'proc_cm_SaveEvent')
BEGIN
    PRINT 'Dropping Procedure proc_cm_SaveEvent'
    DROP  Procedure  proc_cm_SaveEvent
END
GO

PRINT 'Creating Procedure proc_cm_SaveEvent'
GO

CREATE PROCEDURE [dbo].[proc_cm_SaveEvent]
	@pEventId uniqueidentifier
	, @pHtmlPageId uniqueidentifier
	, @pSubjectTxt nvarchar(512)
	, @pStartDttm datetime
	, @pEndDttm datetime
	, @pDescriptionTxt nvarchar(max) = null
	, @pRecurrenceSettings nvarchar(2048) = null
	, @pParentEventId uniqueidentifier = null
AS
BEGIN
	SET NOCOUNT ON

	update
		[dbo].[tbl_event]
	set
		[subject_txt] = @pSubjectTxt
		, [start_dttm] = @pStartDttm
		, [end_dttm] = @pEndDttm
		, [description_txt] = @pDescriptionTxt
		, [recurrence_settings] = @pRecurrenceSettings
		, [parent_event_id] = @pParentEventId
		, [update_dttm] = GETDATE()
	where
		[event_id] = @pEventId

	if @@ROWCOUNT = 0
	begin
		INSERT INTO [dbo].[tbl_event]
		(
			[event_id]
			,[html_page_id]
			,[subject_txt]
			,[start_dttm]
			,[end_dttm]
			,[description_txt]
			,[recurrence_settings]
			,[parent_event_id]
			,[create_dttm]
			,[update_dttm]
		)
		SELECT
			@pEventId
			, @pHtmlPageId
			, @pSubjectTxt
			, @pStartDttm
			, @pEndDttm
			, @pDescriptionTxt
			, @pRecurrenceSettings
			, @pParentEventId
			, GETDATE()
			, GETDATE()
	end
END
GO

GRANT EXEC ON dbo.proc_cm_SaveEvent TO PUBLIC
GO
